package com.kefu.call.service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kefu.call.mapper.CallAvoidDialMapper;
import com.kefu.call.model.CallAvoidDial;
import com.kefu.call.vo.CallAvoidDialInsertVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.vo.ImportResultVo;

/**
 * @author francis
 * @date 2022/06/19
 */
@Service
public class CallAvoidDialService  extends AbstractKefuService<CallAvoidDial> {
    @Autowired
    protected CallAvoidDialMapper callAvoidDialMapper;
	String CALL_AVOID_DIAL="call:avoidDial:%s";
    
	
	public boolean save(CallAvoidDial entity) {
		boolean flag= super.save(entity);
		redisTemplate.opsForHash().put(String.format(CALL_AVOID_DIAL, KefuContext.getKefuContext().getTenantId()), entity.getTelephone(), "1");
		return flag;
	}

	
	public void deleteById(String id) {
		CallAvoidDial callAvoidDial=callAvoidDialMapper.selectById(id);
		if(callAvoidDial!=null){
			redisTemplate.opsForHash().delete(String.format(CALL_AVOID_DIAL, KefuContext.getKefuContext().getTenantId()), callAvoidDial.getTelephone());
		}
		super.deleteById(id);
	}

	
	public ImportResultVo importAvoidDial(List<CallAvoidDialInsertVo> list) {
		
		AtomicInteger nullNum=new AtomicInteger();
		AtomicInteger repeatNum=new AtomicInteger();
		AtomicInteger actualNum=new AtomicInteger();
		
		CallAvoidDial query=new CallAvoidDial();
		query.setTenantId(KefuContext.getKefuContext().getTenantId());
		Set<String> set=callAvoidDialMapper.select(query)
						.stream()
						.map(avoid->avoid.getTelephone())
						.collect(Collectors.toSet());
		
		List<CallAvoidDialInsertVo> list2=list.stream()
						.filter(vo->{
							if(StringUtils.isBlank(vo.getTelephone())){
								nullNum.getAndIncrement();
								return false;
							}
							return true;
						}).collect(Collectors.toList());
		
					list2.stream()
					  .filter(vo->{
						  if(set.contains(vo.getTelephone())) {
							  repeatNum.getAndIncrement();
							  logger.info("免拨打号码{}重复跳过",vo.getTelephone());
							  return false;
						  }
						 set.add(vo.getTelephone());
						  
						  return true;
					  }).map(vo->{
						  return vo.convert();
					  })
					  .forEach(vo->{
						  callAvoidDialMapper.insert(vo);
						  actualNum.getAndIncrement();
						  redisTemplate.opsForHash().put(String.format(CALL_AVOID_DIAL, KefuContext.getKefuContext().getTenantId()), vo.getTelephone(), "1");
					  });
		
		
		return ImportResultVo.builder()
				.expectNum(list.size())
				.invalidNum(nullNum.get())
				.actualNum(actualNum.get())
				.repeatNum(repeatNum.get())
				.build();
	}


}
